package com.wn.date20190813.queue;

import java.util.Iterator;

/**
 * 队列
 * 
 * @author song
 *
 */
public class Queue implements Iterable<Object>
{
	private Object[] data;
	private int size = 0;
	private static final int initalCapacity = 5;

	public Queue()
	{
		data = new Object[initalCapacity];
	}

	public Queue(int num)
	{
		data = new Object[num];
	}

	/**
	 * 清除
	 */
	public void clear()
	{
		size = 0;
		data = new Object[initalCapacity];
	}

	/**
	 * 入队
	 * 
	 * @param obj
	 */
	public boolean Enqueue(Object obj)
	{
		if (data.length == size)
		{
			grow(size + 1);
		}
		data[size++] = obj;
		return true;
	}

	/**
	 * 出队
	 * 
	 * @return
	 */
	public Object Dequeue()
	{
		Object object;
		if (size > 0)
		{
			object = data[0];
			narrow(1);
		} else
		{
			throw new NullPointerException();
		}
		return object;
	}

	// 缩小数组
	private void narrow(int i)
	{
		// 从index=0开始缩小
		Object[] shortObjects = new Object[size - i];
		System.arraycopy(data, 1, shortObjects, 0, shortObjects.length);
		size -= i;
		data = shortObjects;
		shortObjects = null;
	}

	/**
	 * 扩容
	 * 
	 * @param i
	 */
	private void grow(int minLength)
	{
		int newLength = data.length + data.length >> 1;// 扩容1.5
		if (newLength - minLength < 0)
		{
			newLength = minLength;
		}
		Object[] plus = new Object[newLength];
		System.arraycopy(data, 0, plus, 0, data.length);
		data = plus;
		plus = null;
	}

	@Override
	public Iterator<Object> iterator()
	{
		return new Iterator<Object>()
		{

			int count = 0;

			@Override
			public boolean hasNext()
			{
				return size > count;
			}

			@Override
			public Object next()
			{
				return data[count++];
			}

		};
	}
}
